package com.sw.haruka.module.ftp.manager;



import org.apache.ftpserver.FtpServer;
import org.apache.ftpserver.FtpServerFactory;
import org.apache.ftpserver.ftplet.Authority;

import org.apache.ftpserver.listener.ListenerFactory;
import org.apache.ftpserver.usermanager.impl.BaseUser;
import org.apache.ftpserver.usermanager.impl.WritePermission;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.CopyOnWriteArraySet;

public class FtpServerManager {

    private static FtpServerManager manager;

    private boolean isOpen = false;
    private FtpServer mFtpServer;
    private int mPort;
    private Collection<FtpObserver> ftpObservers;

    public static FtpServerManager getInstance() {
        if (manager == null) {
            manager = new FtpServerManager();
        }
        return manager;
    }

    private FtpServerManager() {
        ftpObservers = new CopyOnWriteArraySet<>();
    }


    public void start(String path) { // 初始化
        if (isOpen) {
            return;
        }
        init(path);
        try {
            mFtpServer.start();
            isOpen = true;
            notifyStatusChange();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void init(String path) {
        try {
            FtpServerFactory serverFactory = new FtpServerFactory();

            //设置访问用户名和密码还有共享路径
            BaseUser baseUser = new BaseUser();
            baseUser.setName("anonymous");
            baseUser.setPassword("");
            baseUser.setHomeDirectory(path);

            List<Authority> authorities = new ArrayList<>();
            authorities.add(new WritePermission());
            baseUser.setAuthorities(authorities);
            serverFactory.getUserManager().save(baseUser);

            ListenerFactory factory = new ListenerFactory();
            mPort = getUsefulPort();
            factory.setPort(mPort); //设置端口号 非ROOT不可使用1024以下的端口
            serverFactory.addListener("default", factory.createListener());

            mFtpServer = serverFactory.createServer();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 停止
     */
    public void stop() {
        if (mFtpServer == null || mFtpServer.isStopped()) {
            return;
        }
        mFtpServer.stop();
        mFtpServer = null;
        isOpen = false;
        notifyStatusChange();
    }

    public boolean isOpen() {
        return isOpen;
    }

    public int getPort() {
        return mPort;
    }

    /**
     * 获取可用端口号
     * @return  可用端口号
     */
    public int getUsefulPort() {
//        String host = "localhost";
//        for (int i = 2121;i < 12000;i++) {
//            try {
//                new Socket(host, i);
//            } catch (UnknownHostException e) {
//                e.printStackTrace();
//            } catch (IOException e) {
//                return i;
//            }
//        }
        return 2121;
    }

    //////////////////////////////////观察者模式///////////////////////////
    public void addObserver(FtpObserver observer) {
        ftpObservers.add(observer);
    }

    public void removeObserver(FtpObserver observer) {
        ftpObservers.remove(observer);
    }

    public void notifyStatusChange() {
        for (FtpObserver observer : ftpObservers) {
            observer.statusChange(isOpen);
        }
    }

    public interface FtpObserver {
        void statusChange(boolean offset);
    }
}
